<?php

namespace StudyBuddy\Controllers;

use \StudyBuddy\Utf8String;
use \StudyBuddy\WebPage;
use \StudyBuddy\TitleTokenizer;
use \StudyBuddy\Responder;

/**
 * This controller is used by title auto-complete widgets
 * for search form and by "Ask" form for title auto-complete
 *
 */
class Titlehint extends WebPage
{

	protected $aRequired = array('q');
	
	protected $aData = array();

	protected function main(){
		$disabled = $this->oRegistry->Ini->DISABLE_AUTOCOMPLETE;
		if($disabled){
			exit;
		}

		$this->getData()->sendResult();
	}


	/**
	 * Find data in Mongo
	 * and create array of $this->aData
	 *
	 * @return object $this
	 */
	protected function getData(){

		$aTokens = TitleTokenizer::factory($this->oRequest->getUTF8('q'))->getArrayCopy();

		if(!empty($aTokens)){
			d('looking for something');
			try{
				$cur = $this->oRegistry->Mongo->QUESTIONS->find(array('a_title' => array('$all' => $aTokens), 'a_deleted' => null), array('_id', 'title', 'url', 'intro', 'hts', 'status', 'i_ans', 'ans_s'))
				->sort(array('status' => 1, 'i_ans' => -1))
				->limit(12);
				$this->aData = iterator_to_array($cur, false);
				d('$this->aData: '.print_r($this->aData, 1));
			} catch(\MongoException $e){
				d('MongoException: '.$e->getMessage().' aTokens was: '.print_r($this->aTokens, 1));
			}
		}

		return $this;
	}


	/**
	 * Send result back to client
	 * as JSONP string
	 *
	 * @return string
	 */
	protected function sendResult(){
		$callback =  $this->oRequest->get('callback');
		d('$callback: '.$callback);

		Responder::sendJSONP(array('ac' => $this->aData), $callback);
	}
}
